/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦，本文采用木兰宽松许可证第2版]
 * 
 * https://zhiqim.org/project/zhiqim_products/gitsolo.htm
 *
 * gitsolo is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.gitsolo.dao;

import java.util.List;

import org.zhiqim.gitsolo.GitsoloConstants;
import org.zhiqim.gitsolo.dbo.GitMember;
import org.zhiqim.gitsolo.dbo.GitMemberProject;
import org.zhiqim.gitsolo.dbo.GitProject;
import org.zhiqim.httpd.HttpRequest;
import org.zhiqim.kernel.annotation.AnAlias;
import org.zhiqim.manager.ZmrSessionUser;
import org.zhiqim.manager.dao.ZmrOperatorDao;
import org.zhiqim.manager.dbo.ZmrOperator;
import org.zhiqim.orm.ORM;
import org.zhiqim.orm.dbo.Selector;

/**
 * 项目工程数据访问对象
 *
 * @version v1.0.0 @author zouzhigang 2017-11-9 新建与整理
 */
@AnAlias("GitProjectDao")
public class GitProjectDao implements GitsoloConstants
{
    
    /**
     * 获取操作员所有可见项目列表
     * 
     * @param operatorCode  操作员编码
     * @return              操作员可见项目列表
     * @throws Exception
     */
    public static List<? extends GitProject> getProjectList(HttpRequest request, String operatorCode) throws Exception
    {
        ZmrOperator operator = ORM.table().item(ZmrOperator.class, operatorCode);
        
        if (operator.getOperatorType() <= 1)
        {//超级管理员或管理员，查看所有工程列表
            return ORM.table().list(GitProject.class, new Selector("projectStatus", 0).addOrderbyAsc("projectSeq"));
        }
        else
        {//操作员查看所属的工程列表
            return ORM.view().list(GitMemberProject.class, new Selector("operatorCode", operatorCode).addMust("projectStatus", 0).addOrderbyAsc("projectSeq"));
        }
    }
    
    /**
     * 选择当前工程
     * 
     * @param sessionUser   用户会话对象
     * @param projectId     项目编号
     * @throws Exception    异常
     */
    public static void setProjectId(HttpRequest request, ZmrSessionUser sessionUser, long projectId) throws Exception
    {
        ZmrOperatorDao.addOrUpdateOperatorParam(request, sessionUser.getOperatorCode(), GIT_PROJECT_ID_KEY, projectId);
        ZmrOperator operator = ORM.table().item(ZmrOperator.class, sessionUser.getOperatorCode());
        sessionUser.setOperator(operator);
        
        setProjectMember(request,sessionUser, projectId);
    }
    
    /**
     * 从用户会话中读取默认项目编号
     * 
     * @param request       请求对象
     * @return              项目编号
     * @throws Exception    异常
     */
    public static long getProjectId(HttpRequest request) throws Exception
    {
        ZmrSessionUser sessionUser = request.getSessionUser(ZmrSessionUser.class);
        return sessionUser == null?-1:getProjectId(sessionUser);
    }
    
    /**
     * 从用户会话中读取默认项目编号
     * 
     * @param sessionUser   用户会话对象
     * @return              项目编号
     * @throws Exception    异常
     */
    public static long getProjectId(ZmrSessionUser sessionUser) throws Exception
    {
        return sessionUser.getOperatorParamLong(GIT_PROJECT_ID_KEY);
    }
    
    /**
     * 设置默认项目成员到会话中
     * 
     * @param sessionUser   用户会话对象
     * @param projectId     项目编号
     * @param operatorCode  操作员编码
     * @throws Exception    异常
     */
    public static void setProjectMember(HttpRequest request, ZmrSessionUser sessionUser, long projectId) throws Exception
    {
        Selector selector = new Selector("projectId", projectId);
        selector.addMust("operatorCode", sessionUser.getOperatorCode());
        
        GitMember member = ORM.table().item(GitMember.class, selector);
        sessionUser.setValue(GIT_MEMBER_KEY, member);
    }
    
    /**
     * 删除用户默认项目
     * 
     * @param sessionUser   用户会话对象
     * @param projectId     项目编号
     * @throws Exception    异常
     */
    public static void removeProjectId(HttpRequest request, ZmrSessionUser sessionUser, long projectId) throws Exception
    {
        ZmrOperatorDao.deleteOperatorParam(request, sessionUser.getOperatorCode(), GIT_PROJECT_ID_KEY);
        ZmrOperator operator = ORM.table().item(ZmrOperator.class, sessionUser.getOperatorCode());
        sessionUser.setOperator(operator);
        sessionUser.removeValue(GIT_MEMBER_KEY);
    }
    
    /**
     * 判断是否切换了默认项目
     * 
     * @param request       请求对象
     * @param projectId     传入的项目编号
     * @return              =false表示切换了
     * @throws Exception    异常
     */
    public static boolean chkProjectId(HttpRequest request, long projectId) throws Exception
    {
        if (projectId != getProjectId(request))
        {
            if (request.getParameterBoolean(_PARAM_DIALOG_FRAME_))
                request.returnCloseDialog("您切换了项目或登录超时，请重新选择");
            else if (request.isXMLHttpRequest())
                request.setResponseError("您切换了项目或登录超时，请重新选择");
            else
                request.returnHistory("您切换了项目或登录超时，请重新选择");
            return false;
        }
        
        return true;
    }
    
    /**
     * 激活操作员默认项目
     * 
     * @param sessionUser   用户会话对象
     * @throws Exception    异常
     */
    public static void doActiveProject(HttpRequest request, ZmrSessionUser sessionUser) throws Exception
    {
        doActiveProject(request, getProjectList(request, sessionUser.getOperatorCode()), sessionUser);
    }
    
    /**
     * 激活操作员默认项目
     * 
     * @param sessionUser   用户会话对象
     * @param projectList   项目列表
     * @throws Exception    异常
     */
    public static void doActiveProject(HttpRequest request, List<? extends GitProject> projectList, ZmrSessionUser sessionUser) throws Exception
    {
        long zpmProjectId = sessionUser.getOperatorParamLong(GIT_PROJECT_ID_KEY);
        
        if (projectList.isEmpty())
        {//如果操作员没有一个项目，以前的默认的要取消 -->
            if (zpmProjectId != -1){
                removeProjectId(request, sessionUser, zpmProjectId);
            }
        }
        else
        {//如果操作员有项目
            boolean exist = false;
            if (zpmProjectId != -1)
            {
                for (GitProject proj : projectList)
                {
                    if (proj.getProjectId() != zpmProjectId)
                        continue;
                    
                    setProjectMember(request,sessionUser, zpmProjectId);
                    exist = true;
                    break;
                }
            }
            
            if (!exist)
            {//不存在或未选中，默认选中第一个
                setProjectId(request, sessionUser, projectList.get(0).getProjectId());
            }
        }
    }
}
